import serial,time,yaml,paramiko,sys,os,requests,getopt
from loggerconfig import config_logger
from pingparsing import PingParsing
from pingparsing import PingTransmitter
import pywifi,time
logger = config_logger("check_ssh")
class OperateSsh:
    def __init__(self,remote_ip,username,password):
        self.remote_ip = remote_ip
        self.username = username
        self.password = password

    def connect_ssh(self):
        # 创建SSH对象
        ssh = paramiko.SSHClient()
        # 允许连接不在know_hosts文件中的主机
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            ssh.connect(hostname=self.remote_ip, port=22, username=self.username, password=self.password)
            time.sleep(3)
            return ssh
        
        except:
            logger.info("连接异常")
            # 重新连接远程设备
            retry_count = 0
            max_retries = 6
            while retry_count < max_retries:
                try:
                    ssh.connect(hostname=self.remote_ip, port=22, username=self.username, password=self.password)
                    logger.info("重新连接成功")
                    return ssh
                    # break
                except (paramiko.AuthenticationException, paramiko.SSHException, OSError) as e:
                    logger.info(f"重新连接出错: {e}，正在进行第{retry_count + 1}次重试...")
                    retry_count += 1
                    time.sleep(6)
            if retry_count == max_retries:
                logger.info("达到最大重试次数，无法重新建立连接，请检查相关设置和网络情况。")
                ssh.close()
                return False

    def disconnect_ssh(self,ssh):
        ssh.close()

    def sendcommand_ssh(self,ssh,cmd):
        stdin, stdout, stderr = ssh.exec_command(cmd)
        result_cmd = stdout.read().decode('utf-8')

        logger.info("{} 返回： {}".format(cmd , result_cmd))
        return result_cmd
    

def send_to_qyweixin(line):
    # 你的 Webhook URL
    webhook_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=abc293fb-5657-4580-8a88-9fb29e87d6cf"

    # 消息内容
    data = {
        "msgtype": "text",
        "text": {
            "content": str(line)
        }
    }

    # 发送请求
    response = requests.post(webhook_url, json=data)

    # 输出结果
    print(response.json())

opts,args = getopt.getopt(sys.argv[1:],"f:p:")
for opt,arg in opts:
    if opt in ("-f"):
        line1 = arg
    if opt in ("-p"):
        port = str(arg)


remote_ip = "fe80::ff:fe00:0%{}".format(port)
username = "root"
password = "Yisu10086$"
operatessh = OperateSsh(remote_ip,username,password)

ssh = operatessh.connect_ssh()
while True:
    try:
        operatessh.sendcommand_ssh(ssh,"ls -al")
        time.sleep(5)
    except Exception as e:
        send_to_qyweixin(line1)
        print("ssh连接异常 {}".format(e))
        sys.exit()